﻿using Furion;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Reflection;
using System.Threading.Tasks;
using YFurion.Controllers.Extensions;

namespace YFurion.Controllers
{
    public class OperationLogFilter : IAsyncActionFilter, IOrderedFilter
    {
        /// <summary>
        /// 过滤器排序
        /// </summary>
        public const int FilterOrder = 8888;

        /// <summary>
        /// 排序属性
        /// </summary>
        public int Order => FilterOrder;

        /// <summary>
        /// 操作日志处理程序
        /// </summary>
        private readonly IOperationLogHandler _operationLogHandler;

        /// <summary>
        /// 构造函数
        /// </summary>
        public OperationLogFilter()
        {
            _operationLogHandler = App.GetService<IOperationLogHandler>();
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 调用方法
            ActionExecutedContext resultContext = await next();
            if (resultContext.Exception != null)
            {
                return;
            }

            // 获取动作方法描述器
            ControllerActionDescriptor controllerActionDescriptor = context.ActionDescriptor.AsControllerActionDescriptor();
            // 判断是否贴有操作日志特性
            if (!controllerActionDescriptor.MethodInfo.IsDefined(typeof(OperationLogAttribute)) &&
                !controllerActionDescriptor.MethodInfo.DeclaringType.IsDefined(typeof(OperationLogAttribute))
                )
            {
                return;
            }

            if (_operationLogHandler != null)
            {
                await _operationLogHandler.HandleAsync(resultContext, controllerActionDescriptor);
            }
        }
    }
}
